import { Space, Tag, theme } from "antd";
import { useLocation, useNavigate } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import React, { useEffect, useRef, useState } from "react";
import { closeTag, setCurrentMenu } from '@/store/modules/settingStore'
import "./index.css";

const NavTag = () => {
  const location = useLocation()
  const dispatch = useDispatch()
  const navigate = useNavigate()
  let mainColor = useSelector((state) => state.color.mainColor);
  let tagList = useSelector((state) => state.setting.tagList);
  let currentMenu = useSelector((state) => state.setting.currentMenu);
  console.log('tagList', tagList)
  const {
    token: { colorBgContainer },
  } = theme.useToken();
  const handleClose = (item, index) => {
    console.log('handleClose=>item', item)
    let length = tagList.length - 1
    dispatch(closeTag(item))
    // 若关闭的不是当前的tag，直接删除
    console.log('location.pathname', location.pathname)
    if (item.path !== location.pathname && item.url !== location.pathname) {
      return
    }
    // 删除的是当前选中的菜单tag
    if (index === length) {
      const curDate = tagList[index - 1]
      dispatch(setCurrentMenu(curDate))
      navigate(curDate.url)
    } else {
      // 如果删除的不是当前菜单tag，且他tagList有大于1个数据
      if (tagList.length > 1) {
        const nextData = tagList[index + 1]
        dispatch(setCurrentMenu(nextData))
        navigate(nextData.url)
      }
    }
  };
  const selectTag = (item) => {
    dispatch(setCurrentMenu(item))
    navigate(item.url)
  }
  const setTag = (flag, item, index) => {
    return (
      flag ? 
      <Tag key={item.name} color={mainColor} closeIcon
        onClose={() => handleClose(item, index)}
        onClick={() => selectTag(item)}>
        {item.label}
      </Tag>
      :
      <Tag key={item.name} closeIcon
        onClose={() => handleClose(item, index)}
        onClick={() => selectTag(item)}>
        {item.label}
      </Tag>
    )
  }
  return (
    <Space
      className="nav-tag"
      size={[0, 8]}
      wrap
      style={{
        background: colorBgContainer,
      }}
    >
      {
        currentMenu.name && tagList.map((item,index) => setTag(item.path === currentMenu.path, item, index))
      }
      {/* <Tag closeIcon onClose={() => handleClose()}>
        首页
      </Tag>
      <Tag color={mainColor} closeIcon onClose={() => handleClose()}>
        其他
      </Tag> */}
    </Space>
  );
};
export default NavTag;
